package com.contract.commonlib

import android.text.Spanned
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.contract.commonlib.util.ext.toHtml
import com.contract.commonlib.util.GlideUtil

/**
 *
 * 类描述：
 * 创建人：woochen
 * 创建时间：2020/12/25 7:29 PM
 * 修改备注：
 **/
@BindingAdapter("android:text")
fun setText(view: TextView, text: CharSequence?): Unit {
    val oldText = view.text
    if (text === oldText || text == null && oldText.isEmpty()) {
        return
    }
    if (text is Spanned) {
        if (text == oldText) {
            return  // No change in the spans, so don't set anything.
        }
    } else if (!haveContentsChanged(text, oldText)) {
        return  // No content changes, so don't set anything.
    }
    text?.let {
        if (it.contains("<") && it.contains(">")) {
            view.text = text.toString().toHtml()
        } else view.text = text
    }
}

private fun haveContentsChanged(str1: CharSequence?, str2: CharSequence?): Boolean {
    if (str1 == null != (str2 == null)) {
        return true
    } else if (str1 == null) {
        return false
    }
    val length = str1.length
    if (length != str2!!.length) {
        return true
    }
    for (i in 0 until length) {
        if (str1[i] != str2[i]) {
            return true
        }
    }
    return false
}

@BindingAdapter(value = ["imageUrl", "isCircle", "isRec", "angle"], requireAll = false)
fun loadImage(
    view: ImageView,
    url: Any?,
    isCircle: Boolean = false,
    isRec: Boolean = false,
    angle: Float = 0f
) {
    when {
        isCircle -> {
            GlideUtil.loadCircle(view.context, url, view)
        }
        isRec -> {
            GlideUtil.loadRec(view.context, url, view, angle)
        }
        else -> {
            GlideUtil.load(view.context, url, view)
        }
    }
}